package com.yykj.pharmacist.server.webScoket;

import com.alibaba.fastjson.JSONObject;
import com.yykj.common.util.GsonUtil;
import com.yykj.message.center.client.dto.PrescriptionMessageBodyDTO;
import com.yykj.message.center.client.enums.PrescriptionAction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/client/{userId}")
@Slf4j
@Component
public class PrescriptionPushSocket {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<PrescriptionPushSocket> wsClientMap = new CopyOnWriteArraySet<>();


    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private String userId = "";
    private Integer hospitalId;

    /**
     * 连接建立成功调用的方法
     *
     * @param session 当前会话session
     */
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) {
        this.session = session;
        wsClientMap.add(this);
        addOnlineCount();
        this.userId = userId;
        log.info("新链接加入{},当前链接数为：{}", session.getId(), wsClientMap.size());
    }


    /**
     * 连接关闭
     */
    @OnClose
    public void onClose() {
        wsClientMap.remove(this);
        subOnlineCount();
        log.info("有一链接关闭，当前链接数为：{}", wsClientMap.size());
    }

    /**
     * 收到客户端消息
     *
     * @param message 客户端发送过来的消息
     * @param session 当前会话session
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        JSONObject jsonObject;
        try {
//            log.info("收到websocket消息{}", message);
            jsonObject = JSONObject.parseObject(message);
            String type = jsonObject.getString("type");
            if (StringUtils.isEmpty(type)) {
                return;
            }
            JSONObject json = new JSONObject();
            json.put("type", type);
            switch (type) {
                case "register":
                    this.hospitalId = jsonObject.getInteger("hospitalId");
                    json.put("userId", this.userId);
                    json.put("msg", "注册成功");
                    sendMsgToOne(session, json.toString());
                    break;
                case "heart":
                    json.put("msg", "心跳");
                    sendMsgToOne(session, json.toString());
                    break;
                case "prescription":
                    break;
                default:
                    break;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 发生错误
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.info("wsClientMap发生错误!");
        error.printStackTrace();
    }

    /**
     * 给所有客户端群发消息
     *
     * @param message 消息内容
     * @throws IOException
     */
    public static void sendMsgToAll(String message) throws IOException {
        for (PrescriptionPushSocket item : wsClientMap) {
            item.session.getBasicRemote().sendText(message);
        }
        JSONObject jsonObject = JSONObject.parseObject(message);
        String type = jsonObject.getString("type");
        if ("3".equals(type)) {
            log.info("成功群送mq消息:" + wsClientMap.size());
        }

    }

    /**
     * 发消息
     *
     * @param message 消息内容
     * @throws IOException
     */
    public static void sendMsgToOne(Session session, String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        log.info("成功发送一条消息:{}", message);
    }


    /**
     * 发送自定义消息
     */
    public static void sendInfo(String userId, String message) throws IOException {
        /**
         * 遍历所有用户，找到对应的指定的用户发送消息
         */
        if (!StringUtils.isEmpty(userId)) {
            for (PrescriptionPushSocket item : wsClientMap) {
                if (userId.equals(item.userId)) {
                    log.info("存入的userId" + item.userId);
                    item.session.getBasicRemote().sendText(message);
                }
            }

        } else {
            log.error("用户" + userId + ",不在线！");
        }
    }


    public static void sendInfoToHospital(Integer hospitalId, String message) throws IOException {
        for (PrescriptionPushSocket item : wsClientMap) {
            if (item.hospitalId != null && item.hospitalId.equals(hospitalId)) {
                item.session.getBasicRemote().sendText(message);
            }
        }
    }


    public static void sendPrescriptionStatusChangeToClient(PrescriptionMessageBodyDTO messageBodyDTO) throws IOException {
        log.info("发送Change消息到客户端...开始");
        messageBodyDTO.setType("prescription");
        messageBodyDTO.setAction(PrescriptionAction.change);
        sendInfoToHospital(messageBodyDTO.getHospitalId(), GsonUtil.toJson(messageBodyDTO));
        log.info("发送Change消息到客户端...结束");
    }

    public static void sendPrescriptionCreatedMessageToClient(PrescriptionMessageBodyDTO messageBodyDTO) throws IOException {
        log.info("发送Created消息到客户端...开始");
        messageBodyDTO.setType("prescription");
        messageBodyDTO.setAction(PrescriptionAction.create);
        sendInfoToHospital(messageBodyDTO.getHospitalId(), GsonUtil.toJson(messageBodyDTO));
        log.info("发送Created消息到客户端...结束");
    }


    public static synchronized int getOnlineCount() {
        return PrescriptionPushSocket.onlineCount;
    }

    public static synchronized void addOnlineCount() {
        PrescriptionPushSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        PrescriptionPushSocket.onlineCount--;
    }


}
